#pragma once
#include "Log.hpp"
#include "uncopyable.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Inet.hpp"

// UDP_echo_Server 的服务端：接受并显示客户端发送的信息，最终把信息发回客户端
using namespace log_ddsm;
enum
{
    default_sockfd = -1,
    default_localport = -1,
    socket_err = 1,
    bind_err = 3,
    SIZE = 2048
};

class UdpServer : public uncopyable // 服务器一般无法拷贝，赋值
{
public:
    UdpServer(uint16_t localport = default_localport)
        : _sockfd(default_sockfd)
        , _localport(localport)
        , _isrunning(false)
    {
    }
    void Init()//创建套接字并绑定
    {
        // 创建一个udp的网络套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket creat fail!\n");
            exit(socket_err);
        }
        LOG(DEBUG, "socket creat success | socket = %d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));

        //填写本地的ip地址和端口号
        local.sin_family = AF_INET; 
        local.sin_port = htons(_localport);
        // local.sin_addr.s_addr = inet_addr(_localip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        //绑定socket和ip 端口号
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(FATAL,"bind fail!\n");
            exit(bind_err);
        }
        LOG(DEBUG,"socket bind success\n");
    }
    void Start()//不断收发信息
    {
        _isrunning = true;
        char inbuf[SIZE] = {0};
        while(1)
        {
            //do service
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            //len，输出型参数，表明peer字段的长度
            ssize_t n = recvfrom(_sockfd,inbuf,sizeof(inbuf)-1,0,(struct sockaddr*)&peer,&len);
            if(n > 0)
            {
                //将网络序列转化为主机序列
                Inet inet(peer);
                //读取成功
                inbuf[n] = '\0';
                std::cout<<"["<<inet.IP()<<" "<<inet.PORT()<<"] :"<<inbuf<<std::endl;
                std::string echo_string = "[udp_sever echo] ";
                echo_string += inbuf;

                //把接收到的字符串返回给客户端
                sendto(_sockfd,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&peer,len);
            }
        }
    }
    ~UdpServer()
    {
        if(_sockfd > default_sockfd)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;//网络套接字，类似于一个文件fd
    uint16_t _localport;//本进程的端口号

    // std::string _localip;//本地的ip ---设置为任意 0

    bool _isrunning;//服务器是否正在运行
};